package com.dime.physical.service.impl;

import java.beans.Transient;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.dime.basic.api.RemoteBaseCombService;
import com.dime.basic.api.domain.DimeBasecomb;
import com.dime.basic.api.domain.DimeBaseharm;
import com.dime.basic.api.model.Combo;
import com.dime.mninterface.api.RemoteHealth100Service;
import com.dime.mninterface.api.model.*;
import com.dime.physical.domain.DimeBasepackage;
import com.dime.physical.domain.DimeBasepackagecomb;
import com.dime.physical.domain.DimeBasepackageharm;
import com.dime.physical.domain.dto.CompanyDto;
import com.dime.physical.domain.dto.PhysicalCombDto;
import com.dime.physical.domain.dto.PhysicalharmsDto;
import com.dime.physical.mapper.DimeBasepackageMapper;
import com.dime.physical.mapper.DimeBasepackagecombMapper;
import com.dime.physical.mapper.DimeBasepackageharmMapper;
import com.dime.physical.service.IDimeBasepackageService;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.uuid.IdUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dime.physical.mapper.DimeBasecompanyMapper;
import com.dime.physical.domain.DimeBasecompany;
import com.dime.physical.service.IDimeBasecompanyService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 体检单位管理Service业务层处理
 * 
 * @author Tiny
 * @date 2023-09-14
 */
@Service
public class DimeBasecompanyServiceImpl implements IDimeBasecompanyService {
    @Autowired
    private DimeBasecompanyMapper dimeBasecompanyMapper;

    @Autowired
    private RemoteHealth100Service remoteHealth_100Service;

    @Autowired
    private DimeBasepackagecombMapper dimeBasepackagecombMapper;

    @Autowired
    private DimeBasepackageMapper dimeBasepackageMapper;

    @Autowired
    private DimeBasepackageharmMapper dimeBaseharmMapper;

    @Autowired
    private RemoteBaseCombService remoteBaseCombService;

    @Autowired
    private IDimeBasepackageService dimeBasepackageService;
    /**
     * 查询体检单位管理
     *
     * @param id 体检单位管理主键
     * @return 体检单位管理
     */
    @Override
    public DimeBasecompany selectDimeBasecompanyById(String id) {
        return dimeBasecompanyMapper.selectDimeBasecompanyById(id);
    }

    /**
     * 查询体检单位管理列表
     *
     * @param dimeBasecompany 体检单位管理
     * @return 体检单位管理
     */
    @Override
    public List<DimeBasecompany> selectDimeBasecompanyList(DimeBasecompany dimeBasecompany) {

        List<DimeBasecompany> dimeBasecompanies=dimeBasecompanyMapper.selectDimeBasecompanyList(dimeBasecompany);
        return dimeBasecompanies;
    }

    /**
     * 新增体检单位管理
     *
     * @param dimeBasecompany 体检单位管理
     * @return 结果
     */
    @Override
    public int insertDimeBasecompany(DimeBasecompany dimeBasecompany) {

        dimeBasecompany.setId(IdUtils.fastUUID());
        dimeBasecompany.setCreateBy(SecurityUtils.getUsername());
        dimeBasecompany.setCreateTime(DateUtils.getNowDate());
        return dimeBasecompanyMapper.insertDimeBasecompany(dimeBasecompany);
    }

    /**
     * 修改体检单位管理
     *
     * @param dimeBasecompany 体检单位管理
     * @return 结果
     */
    @Override
    public int updateDimeBasecompany(DimeBasecompany dimeBasecompany) {
        dimeBasecompany.setUpdateTime(DateUtils.getNowDate());
        dimeBasecompany.setUpdateBy(SecurityUtils.getUsername());
        return dimeBasecompanyMapper.updateDimeBasecompany(dimeBasecompany);
    }

    /**
     * 批量删除体检单位管理
     *
     * @param ids 需要删除的体检单位管理主键
     * @return 结果
     */
    @Override
    public int deleteDimeBasecompanyByIds(String[] ids) {
        return dimeBasecompanyMapper.deleteDimeBasecompanyByIds(ids);
    }

    /**
     * 删除体检单位管理信息
     *
     * @param id 体检单位管理主键
     * @return 结果
     */
    @Override
    public int deleteDimeBasecompanyById(String id) {
        return dimeBasecompanyMapper.deleteDimeBasecompanyById(id);
    }



    @Override
    public CompanyDto getBqCompanyBySoaNo(String SoaNo) {
        String shopCode = SecurityUtils.getShopId();
        OrderRequestBody requestBody = new OrderRequestBody();
        requestBody.setBranchCode(shopCode);
        requestBody.setClientSource(0L);
        requestBody.setVerifyScope(0L);
        requestBody.setOrderCode(SoaNo);
        //单位信息
        MNResponse<MNCompany> tCompany = remoteHealth_100Service.getCompany(requestBody);
        CompanyDto companyDto = new CompanyDto();
        if (Objects.equals(tCompany.getCode(), "000000")) {
            MNCompany company = tCompany.getData();

            companyDto.setId(IdUtils.fastUUID());
            companyDto.setCompanyCode(company.getCorpCode());
            companyDto.setCompanyName(company.getCorpName());
            companyDto.setAddress(company.getCorpAddress());
            companyDto.setContacts(company.getContacts());
            companyDto.setTelephone(company.getContactNumber());
            companyDto.setNewCorp(company.getNewCorp());
            companyDto.setBeginDate(DateUtils.parseDate(company.getBeginDate()));
            companyDto.setEndDate(DateUtils.parseDate(company.getEndDate()));
            companyDto.setContractType(company.getContractType().toString());
            companyDto.setBasePayType(company.getBasePayType());
            companyDto.setSalesmanId(companyDto.getSalesmanId());
            companyDto.setUserName(companyDto.getUserName());
            companyDto.setUserMobile(companyDto.getUserMobile());
            companyDto.setOrderType(company.getOrderType());
            companyDto.setRemark(company.getRemark());
            companyDto.setRemark2(companyDto.getRemark2());
            companyDto.setRemark3(companyDto.getRemark3());
            companyDto.setShopCode(shopCode);
            //方案信息
            MNResponse<List<MNOrderDetail>> tOrder = remoteHealth_100Service.getOrder(requestBody);
            if (Objects.equals(tOrder.getCode(), "000000")) {
                companyDto.basepackageList = new ArrayList<>();

                List<MNOrderDetail> orderDetails = tOrder.getData();
                for (MNOrderDetail order : orderDetails) {

                    DimeBasepackage basepackage = new DimeBasepackage();
                    basepackage.setId(IdUtils.fastUUID());
                    basepackage.setOrderCode(order.getOrderCode());
                    basepackage.setCompanyNameId(companyDto.getId());
                    basepackage.setPackageCode(order.getPackageCode());
                    basepackage.setPackageName(order.getPackageName());
                    basepackage.setPackageOriginalPrice(BigDecimal.valueOf(order.getSalePrice()));
                    basepackage.setPackageDiscountPrice(BigDecimal.valueOf(order.getPrice()));
                    basepackage.setStartDate(DateUtils.parseDate(company.getBeginDate()));
                    basepackage.setEndDate(DateUtils.parseDate(company.getEndDate()));
                    basepackage.dimeBaseharmList = new ArrayList<>();
                    companyDto.basepackageList.add(basepackage);
                    basepackage.setShopCode(shopCode);
                    if (order.getSoaPackageItemDTOList() != null && order.getSoaPackageItemDTOList().size() > 0) {
                        basepackage.physicalCombDtoList = new ArrayList<>();
                        //循环 SoaPackageItemDTOList
                        for (SoaPackageItemDTO item : order.getSoaPackageItemDTOList()) {

                            PhysicalCombDto physicalCombDto = new PhysicalCombDto();
                            physicalCombDto.setId(IdUtils.fastUUID());
                            physicalCombDto.setCombCode(item.getProductCode());
                            physicalCombDto.setCombName(item.getProductName());
                            physicalCombDto.setCombPrice(BigDecimal.valueOf(item.getPrice()));
                            basepackage.physicalCombDtoList.add(physicalCombDto);
                        }
                    }
                }


            }


        }

        else {
            throw new ServiceException(tCompany.getMsg());

        }
        return companyDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveCompany(CompanyDto companyDto) {
        int rows = 0;
        DimeBasecompany dimeBasecompany = companyDto;
        try {

            //判断单位信息是否存在
            DimeBasecompany dimeBasecompany1 = dimeBasecompanyMapper.selectDimeBasecompanyByCode(dimeBasecompany.getCompanyCode());
            if (dimeBasecompany1 == null) {
                rows = dimeBasecompanyMapper.insertDimeBasecompany(dimeBasecompany);
            } else {
                dimeBasecompany.setId(dimeBasecompany1.getId());
            }

            List<DimeBasepackage> dimeBasepackages = companyDto.basepackageList;
            //循环保存方案
            for (DimeBasepackage basepackage : dimeBasepackages) {
                DimeBasepackage dimeBasepackage = dimeBasepackageMapper.selectDimeBasepackageByCode(basepackage.getPackageCode());
                if (dimeBasepackage != null)
                {
                    rows++;
                    continue;
                }


                basepackage.setCompanyNameId(dimeBasecompany.getId());
                rows += dimeBasepackageMapper.insertDimeBasepackage(basepackage);
                //循环保存方案组合
                List<PhysicalCombDto> physicalCombDtoList = basepackage.physicalCombDtoList;

                if (!validateComb(physicalCombDtoList)) {
                    throw new ServiceException("基础项目信息验证失败！");
                }

                for (PhysicalCombDto physicalCombDto : physicalCombDtoList) {
                    DimeBasepackagecomb dimeBasepackagecomb = new DimeBasepackagecomb();
                    dimeBasepackagecomb.setId(IdUtils.fastUUID());
                    dimeBasepackagecomb.setCombCode(physicalCombDto.getCombCode());
                    dimeBasepackagecomb.setCombName(physicalCombDto.getCombName());
                    dimeBasepackagecomb.setDimeBasepackageid(basepackage.getId());
                    dimeBasepackagecomb.setDimeBasecombid(physicalCombDto.getId());
                    rows += dimeBasepackagecombMapper.insertDimeBasepackagecomb(dimeBasepackagecomb);
                }
                List<DimeBaseharm> baseharms = basepackage.dimeBaseharmList;
                for (DimeBaseharm physicalharmsDto : baseharms) {

                    DimeBasepackageharm dimeBasepackageharms = new DimeBasepackageharm();
                    dimeBasepackageharms.setId(IdUtils.fastUUID());
                    dimeBasepackageharms.setDimeBaseharmid(physicalharmsDto.getId());
                    dimeBasepackageharms.setHarmName(physicalharmsDto.getHamName());
                    dimeBasepackageharms.setHarmCode(physicalharmsDto.getHamrCode());
                    dimeBasepackageharms.setDimeBasepackageid(basepackage.getId());

                    rows += dimeBaseharmMapper.insertDimeBasepackageharm(dimeBasepackageharms);
                }


            }

        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DimeBasecompany editSearchBQCompany(DimeBasecompany basecompany) {

        DimeBasecompany  dimeBasecompany=selectDimeBasecompanyById(basecompany.getId());
        List<DimeBasepackage>dimeBasepackages=dimeBasepackageService.selectDimeBasepackageByCompanyid(dimeBasecompany.getId());
        dimeBasecompany.setBasepackageList(dimeBasepackages);
        return dimeBasecompany;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DimeBasecompany editSearchBQCompanyById(String id) {
        DimeBasecompany dimeBasecompany = selectDimeBasecompanyById(id);
        List<DimeBasepackage> dimeBasepackages = dimeBasepackageService.selectDimeBasepackageByCompanyid(id);
        dimeBasecompany.setBasepackageList(dimeBasepackages);
        return dimeBasecompany;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int editSaveBQCompany(DimeBasecompany dimeBasecompany) {

        int rows = 0;
        dimeBasecompany.setUpdateTime(DateUtils.getNowDate());
        dimeBasecompany.setUpdateBy(SecurityUtils.getUsername());
        if (dimeBasecompany.getBasepackageList() != null && dimeBasecompany.getBasepackageList().size() > 0) {
            for (DimeBasepackage basepackage : dimeBasecompany.getBasepackageList()) {

                dimeBaseharmMapper.deleteDimeBasepackageharmBypackageid(basepackage.getId());
                if (basepackage.getDimeBaseharmList() != null && basepackage.getDimeBaseharmList().size() > 0) {
                    for (DimeBaseharm baseharm : basepackage.getDimeBaseharmList()) {
                        DimeBasepackageharm dimeBasepackageharms = new DimeBasepackageharm();
                        dimeBasepackageharms.setId(IdUtils.fastUUID());
                        dimeBasepackageharms.setDimeBaseharmid(baseharm.getId());
                        dimeBasepackageharms.setHarmCode(baseharm.getHamrCode());
                        dimeBasepackageharms.setHarmName(baseharm.getHamName());
                        dimeBasepackageharms.setDimeBasepackageid(basepackage.getId());
                        dimeBaseharmMapper.insertDimeBasepackageharm(dimeBasepackageharms);
                    }
                }
                dimeBasepackageMapper.updateDimeBasepackage(basepackage);


            }
        }

        rows = dimeBasecompanyMapper.updateDimeBasecompany(dimeBasecompany);
        return rows;
    }


    private boolean validateComb(List<PhysicalCombDto> physicalCombDtoList) {
        for (PhysicalCombDto combDto : physicalCombDtoList) {
            R<Combo> _comb = remoteBaseCombService.getComb(combDto.getCombCode(), SecurityConstants.INNER);
            if (_comb.getCode() != R.FAIL && _comb.getData() != null) {
                combDto.setId(_comb.getData().getId());
            } else {
                throw new ServiceException(combDto.getCombName() + ">未查询到项目信息！");
            }

        }
        return true;

    }
}
